package com.rfid;

import com.rfid.analysis.Message;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Administrator
 * @date 2020/9/16
 * 线程循环拉取队列里面的数据丢给消息处理者进行处理
 */
public class DealDataRunnable implements Runnable {
    private LinkedBlockingDeque<byte[]> mDeque;
    private volatile boolean isRunning = true;
    private boolean isParser = false;
    private final Message mMessage;

    public DealDataRunnable(Message message) {
        mDeque = new LinkedBlockingDeque<>();
        mMessage = message;
    }

    @Override
    public void run() {
        while (isRunning) {
            if (!isParser) {
                //防止poll数据过长导致解析时间过长
                isParser = true;
                try {
                    byte[] data = mDeque.take();
                    mMessage.put(data);
                    //从当前处理者开始处理数据
                    mMessage.getCurrentNodeHandler().handleRequest(mMessage);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
                isParser = false;
            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }

        }
    }

    public void putData(byte[] data) {
        mDeque.offer(data);
    }

    public void stop() {
        isRunning = false;
    }
}